//
//  MultiCameraTestViewController.m
//  DJISdkDemo
//
//  Created by AIC on 2020/12/18.
//  Copyright © 2020 DJI. All rights reserved.
//

#import "MultiCameraTestViewController.h"
#import "DemoUtility.h"
#import "VideoPreviewerSDKAdapter.h"
#import <DJIWidget/DJIVideoPreviewer.h>
#import <DJISDK/DJISDK.h>


@interface MultiCameraTestViewController ()<DJIVideoFeedSourceListener,DJIVideoFeedListener>

@property(assign,nonatomic) BOOL primaryVideoFeedPlaying;
@property(assign,nonatomic) BOOL secondaryVideoFeedPlaying;

@property (weak, nonatomic) IBOutlet UIView *primaryPlayView;
@property (weak, nonatomic) IBOutlet UIView *secondaryPlayView;
@property (weak, nonatomic) IBOutlet UIButton *primaryPlayBtn;
@property (weak, nonatomic) IBOutlet UIButton *secondaryPlayBtn;

@property (weak, nonatomic) IBOutlet UILabel *primaryPhysicalSource;
@property (weak, nonatomic) IBOutlet UILabel *primaryCamera;
@property (weak, nonatomic) IBOutlet UILabel *primaryActiveStatus;
@property (weak, nonatomic) IBOutlet UISwitch *primaryFrameCtrl;
@property (weak, nonatomic) IBOutlet UILabel *primaryRealTimeReceive;

@property (weak, nonatomic) IBOutlet UILabel *secondaryPhysicalSource;
@property (weak, nonatomic) IBOutlet UILabel *secondaryCamera;
@property (weak, nonatomic) IBOutlet UILabel *secondaryActiveStatus;
@property (weak, nonatomic) IBOutlet UISwitch *seconadryFrameCtrl;
@property (weak, nonatomic) IBOutlet UILabel *secondaryRealtimeReceive;

@property (weak, nonatomic) IBOutlet UILabel *closeAllSourceResult;

@property (weak, nonatomic) IBOutlet UILabel *assignSourceResult;

@property (weak, nonatomic) IBOutlet UISegmentedControl *assignSourceSegment;
@property (weak, nonatomic) IBOutlet UISegmentedControl *ControlledGimbalSegment;

@end

@implementation MultiCameraTestViewController{
    VideoPreviewerSDKAdapter *primaryPreviewerAdapter;
    DJIVideoPreviewer  *primaryVideoPreviewer;
    
    VideoPreviewerSDKAdapter *secondaryPreviewerAdapter;
    DJIVideoPreviewer  *secondaryVideoPreviewer;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _assignSourceSegment.selectedSegmentIndex = 0;
    _primaryFrameCtrl.on = NO;
    _seconadryFrameCtrl.on = NO;
    
//    WeakRef(weakSelf);
//    [[DemoComponentHelper fetchAirLink].ocuSyncLink assignSourceToPrimaryChannel:DJIVideoFeedPhysicalSourceLeftCamera secondaryChannel:DJIVideoFeedPhysicalSourceRightCamera withCompletion:^(NSError * _Nullable error) {
//        self->_assignSourceResult.text= error?[NSString stringWithFormat:@"分配失败：%@",error]:@"分配成功";
//        DJIVideoFeeder*videoFeeder = [DemoComponentHelper fetchProduct].videoFeeder;
//        [weakSelf updateSourecInfo:videoFeeder.primaryVideoFeed.physicalSource videoFeed:videoFeeder.primaryVideoFeed];
//        [weakSelf updateSourecInfo:videoFeeder.secondaryVideoFeed.physicalSource videoFeed:videoFeeder.secondaryVideoFeed];
//    }];
    
    DJIVideoFeeder*videoFeeder = [DemoComponentHelper fetchProduct].videoFeeder;
    [self updateSourecInfo:videoFeeder.primaryVideoFeed.physicalSource videoFeed:videoFeeder.primaryVideoFeed];
    [self updateSourecInfo:videoFeeder.secondaryVideoFeed.physicalSource videoFeed:videoFeeder.secondaryVideoFeed];
    
    
    
    //DJIVideoFeeder*videoFeeder = [DemoComponentHelper fetchProduct].videoFeeder;
    
    primaryVideoPreviewer = [[DJIVideoPreviewer alloc]init];
    [primaryVideoPreviewer setView:_primaryPlayView];
    primaryPreviewerAdapter = [VideoPreviewerSDKAdapter adapterWithVideoPreviewer:primaryVideoPreviewer andVideoFeed:videoFeeder.primaryVideoFeed];
    
    
    secondaryVideoPreviewer = [[DJIVideoPreviewer alloc]init];
    [secondaryVideoPreviewer setView:_secondaryPlayView];
    secondaryPreviewerAdapter = [VideoPreviewerSDKAdapter adapterWithVideoPreviewer:secondaryVideoPreviewer
                                                                       andVideoFeed:videoFeeder.secondaryVideoFeed];
    
    [videoFeeder addVideoFeedSourceListener:self];
    
    [videoFeeder.primaryVideoFeed addListener:self withQueue:nil];
    [videoFeeder.secondaryVideoFeed addListener:self withQueue:nil];
    
    [[DemoComponentHelper fetchRemoteController] setControllingGimbalIndex:0 withCompletion:nil];
}

- (IBAction)primaryFrameCtrlSwitchAction:(UISwitch*)sender {
    primaryVideoPreviewer.frameControlHandler = sender.on ? primaryPreviewerAdapter : nil;
}

- (IBAction)secondaryFrameCtrlSwitchAction:(UISwitch* )sender {
    secondaryVideoPreviewer.frameControlHandler = sender.on ? secondaryPreviewerAdapter : nil;
}

// 播放/停止播放，主视频流
- (IBAction)primaryPlayAction:(id)sender {
    if (_primaryVideoFeedPlaying) {
        [primaryPreviewerAdapter stop];
        [primaryVideoPreviewer close];
        [_primaryPlayBtn setTitle:@"播放" forState:UIControlStateNormal];
    }else{
        [primaryPreviewerAdapter start];
        [primaryVideoPreviewer start];
        [_primaryPlayBtn setTitle:@"停止" forState:UIControlStateNormal];
    }
    _primaryVideoFeedPlaying = !_primaryVideoFeedPlaying;
}

// 播放/停止播放，副视频流
- (IBAction)secodaryPlayAction:(id)sender {
    if (_secondaryVideoFeedPlaying) {
        [secondaryPreviewerAdapter stop];
        [secondaryVideoPreviewer close];
        [_secondaryPlayBtn setTitle:@"播放" forState:UIControlStateNormal];
    }else{
        [secondaryPreviewerAdapter start];
        [secondaryVideoPreviewer start];
        [_secondaryPlayBtn setTitle:@"停止" forState:UIControlStateNormal];
    }
    
    _secondaryVideoFeedPlaying = !_secondaryVideoFeedPlaying;
}

// 关闭说有视频源
- (IBAction)closeAllSourceAction:(id)sender {
    _closeAllSourceResult.text = nil;
    [[DemoComponentHelper fetchAirLink].ocuSyncLink closeAllVideoSourcesWithCompletion:^(NSError * _Nullable error) {
        self->_closeAllSourceResult.text = error?  [NSString stringWithFormat:@"%@",error]:@"关闭成功";
        if(error)
            DJILogError(@"%@",error);
    }];
}

// 分配VideoFeed的物理源
- (IBAction)changeVideoFeedSourceAction:(UISegmentedControl *)sender {
    DJIVideoFeedPhysicalSource primary = DJIVideoFeedPhysicalSourceLeftCamera;
    DJIVideoFeedPhysicalSource secondary = DJIVideoFeedPhysicalSourceRightCamera;
    
    if(sender.selectedSegmentIndex ==1){
        primary = DJIVideoFeedPhysicalSourceRightCamera;
        secondary = DJIVideoFeedPhysicalSourceLeftCamera;
    }else if(sender.selectedSegmentIndex ==2){
        primary = DJIVideoFeedPhysicalSourceRightCamera;
        secondary = DJIVideoFeedPhysicalSourceFPVCamera;
    }else if(sender.selectedSegmentIndex ==3){
        primary = DJIVideoFeedPhysicalSourceLeftCamera;
        secondary = DJIVideoFeedPhysicalSourceFPVCamera;
    }
    
    WeakRef(weakSelf);
    _assignSourceResult.text = nil;
    [[DemoComponentHelper fetchAirLink].ocuSyncLink assignSourceToPrimaryChannel:primary secondaryChannel:secondary withCompletion:^(NSError * _Nullable error) {
        self->_assignSourceResult.text= error?[NSString stringWithFormat:@"分配失败：%@",error]:@"分配成功";
        if(error)
            DJILogError(@"%@",error);
    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        DJIVideoFeeder*videoFeeder = [DemoComponentHelper fetchProduct].videoFeeder;
        [weakSelf updateSourecInfo:videoFeeder.primaryVideoFeed.physicalSource videoFeed:videoFeeder.primaryVideoFeed];
        [weakSelf updateSourecInfo:videoFeeder.secondaryVideoFeed.physicalSource videoFeed:videoFeeder.secondaryVideoFeed];
    });
}

- (IBAction)controlledGimbalIndexChanged:(UISegmentedControl *)sender {
    [[DemoComponentHelper fetchRemoteController] setControllingGimbalIndex: sender.selectedSegmentIndex withCompletion:^(NSError * _Nullable error) {
            
    }];
}

- (IBAction)printVideoFeedInfo:(id)sender {
    DJIVideoFeeder *feeder =[DemoComponentHelper fetchProduct].videoFeeder;
    NSString *primaryInfo = @"Primary:";
    primaryInfo =[primaryInfo stringByAppendingString:[self displayVideoFeedPhysicalSource:feeder.primaryVideoFeed.physicalSource]];
    primaryInfo =[primaryInfo stringByAppendingString:@" status:"];
    primaryInfo =[primaryInfo stringByAppendingString:feeder.primaryVideoFeed.active?@"active":@"inactive"];
    primaryInfo =[primaryInfo stringByAppendingString:@" Camera:"];
    primaryInfo =[primaryInfo stringByAppendingString:[self CameraForideoFeedPhysicalSource:feeder.primaryVideoFeed.physicalSource]];
    
    
    NSString *secondaryInfo = @"Secondary:";
    secondaryInfo =[secondaryInfo stringByAppendingString:[self displayVideoFeedPhysicalSource:feeder.secondaryVideoFeed.physicalSource]];
    secondaryInfo =[secondaryInfo stringByAppendingString:@" status:"];
    secondaryInfo =[secondaryInfo stringByAppendingString:feeder.secondaryVideoFeed.active?@"active":@"inactive"];
    secondaryInfo =[secondaryInfo stringByAppendingString:@" Camera:"];
    secondaryInfo =[secondaryInfo stringByAppendingString:[self CameraForideoFeedPhysicalSource:feeder.secondaryVideoFeed.physicalSource]];
    
    DJILogInfo(primaryInfo);
    DJILogInfo(secondaryInfo);
    
}

#pragma mark DJIVideoFeedSourceListener & DJIVideoFeedListener

- (void)updateSourecInfo:(DJIVideoFeedPhysicalSource)physicalSource videoFeed:(DJIVideoFeed * _Nonnull)videoFeed {

    NSString *status = videoFeed.active ? @"active" : @"inactive";
    if(videoFeed == [DemoComponentHelper fetchProduct].videoFeeder.primaryVideoFeed){
        _primaryPhysicalSource.text =[self displayVideoFeedPhysicalSource:physicalSource];
        _primaryCamera.text =[self CameraForideoFeedPhysicalSource:physicalSource];
        _primaryActiveStatus.text = status;
    }else{
        _secondaryPhysicalSource.text =[self displayVideoFeedPhysicalSource:physicalSource];
        _secondaryCamera.text =[self CameraForideoFeedPhysicalSource:physicalSource];
        _secondaryActiveStatus.text = status;
    }
}

-(void)videoFeed:(DJIVideoFeed *)videoFeed didChangePhysicalSource:(DJIVideoFeedPhysicalSource)physicalSource{
    [self updateSourecInfo:physicalSource videoFeed:videoFeed];
}

-(void)videoFeed:(DJIVideoFeed *)videoFeed didChangeActiveStatus:(BOOL)active {
    NSString *status = active ? @"active" : @"inactive";
    if(videoFeed == [DemoComponentHelper fetchProduct].videoFeeder.primaryVideoFeed){
        _primaryActiveStatus.text = status;
    }else{
        _secondaryActiveStatus.text = status;
    }
}

- (void)videoFeed:(nonnull DJIVideoFeed *)videoFeed didUpdateVideoData:(nonnull NSData *)videoData {
    if(videoFeed == [DemoComponentHelper fetchProduct].videoFeeder.primaryVideoFeed){
        _primaryRealTimeReceive.text = [NSString stringWithFormat:@"%lu",(unsigned long)videoData.length];
        //NSLog(@"primary:%lu",(unsigned long)videoData.length);
    }else{
        _secondaryRealtimeReceive.text = [NSString stringWithFormat:@"%lu",(unsigned long)videoData.length];
        //NSLog(@"secondary:%lu",(unsigned long)videoData.length);
    }
}


#pragma mark Utility
-(NSString*)displayVideoFeedPhysicalSource:(DJIVideoFeedPhysicalSource)source{
    NSString* name = @"Unsupported";
    switch (source) {
        case DJIVideoFeedPhysicalSourceFPVCamera:
            name = @"FPV";
            break;
        case DJIVideoFeedPhysicalSourceLeftCamera:
            name = @"Left Camera";
            break;
        case DJIVideoFeedPhysicalSourceRightCamera:
            name = @"Right Camera";
            break;
        case DJIVideoFeedPhysicalSourceTopCamera:
            name = @"Top Camera";
            break;
        case DJIVideoFeedPhysicalSourceUnknown:
            name = @"Unknown";
            break;
        default:
            name = [NSString stringWithFormat:@"Unsupported:%ld",(long)source];
            break;
    }
    return name;
}



-(NSString*)CameraForideoFeedPhysicalSource:(DJIVideoFeedPhysicalSource)source{
    
    if(source == DJIVideoFeedPhysicalSourceFPVCamera)
        return @"FPV";
    
    int index = -1;
    if(source == DJIVideoFeedPhysicalSourceLeftCamera)
        index = 0;
    else if(source == DJIVideoFeedPhysicalSourceRightCamera)
        index = 1;
    else if(source == DJIVideoFeedPhysicalSourceTopCamera)
        index = 2;
  
    NSArray* cameras =[DemoComponentHelper fetchCameras];
    for (DJICamera *camera in cameras) {
        if(camera.index == index){
            return camera.displayName;
        }
    }
    return @"Unknown";
}



@end
